﻿using AutoCommunication.Helper;
using Newtonsoft.Json;
using System;
using System.ComponentModel;
using System.Net;
using System.Net.Sockets;

namespace AutoCommunication.Base
{
    /// <summary>
    /// Socket基类
    /// </summary>
    public abstract class BaseSocketDevice<T> : BaseDevice<T> where T : BaseVariable
    {
        public BaseSocketDevice()
        {
        }

        #region 字段

        /// <summary>
        /// Socket实例
        /// </summary>
        protected Socket socket;

        #endregion 字段

        #region 属性

        /// <summary>
        /// IP地址
        /// </summary>
        [JsonProperty("IP地址"), DisplayName("IP地址"), Category("设备信息")]
        public abstract string IpAddress { get; set; }

        /// <summary>
        /// IP地址
        /// </summary>
        [JsonProperty("端口"), DisplayName("端口号"), Category("设备信息")]
        public abstract int Port { get; set; }

        /// <summary>
        /// 是否为plc地址 默认false;modbus协议中可能需要
        /// </summary>
        [JsonProperty("是否为plc地址"), DisplayName("是否为plc地址"), Category("设备信息")] public bool plcAddresses { get; set; } = false;

        /// <summary>
        /// 连接ip地址和端口
        /// </summary>
        [Browsable(false)]
        [JsonIgnore]
        public IPEndPoint IpEndPoint { get; set; }

        [JsonIgnore, Browsable(false)]
        public override bool Connected { get; set; } = false;

        //  public override bool Connected => socket?.Connected ?? false;

        #endregion 属性

        #region 方法

        /// <summary>
        /// 关闭Socket连接
        /// </summary>
        /// <returns></returns>
        [Obsolete]
        protected override Result Disconnect()
        {
            Result result = new Result();
            try
            {
                socket?.SafeClose();
                return result;
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Err = ex.Message;
                result.Exception = ex;
                Loger?.Invoke($"{Name}断开连接失败:{ex.Message}", ex);
                return result;
            }
        }

        #endregion 方法
    }
}